// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.ooops;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import com.dustedpixels.common.AdapterSupplier;

/**
 * Implementation of {@code Inliner}.
 * 
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
final class OoopsImpl implements Ooops {
  private final AdapterSupplier<ClassVisitor> inliningAdapterSupplier;

  public OoopsImpl(AdapterSupplier<ClassVisitor> inliningAdapterSupplier) {
    this.inliningAdapterSupplier = inliningAdapterSupplier;
  }
  
  public void process(String className,
      ClassDataSupplier inputClassDataSupplier,
      ClassDataReceiver outputClassDataReceiver) {
   
    byte[] classData = inputClassDataSupplier.loadClassData(className);
    if (classData == null) {
      throw new RuntimeException("No class found: " + className);
    }
    ClassReader classReader = new ClassReader(classData);
    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ClassVisitor inliningVisitor = inliningAdapterSupplier.get(classWriter);
    classReader.accept(inliningVisitor, 0);
    classData = classWriter.toByteArray();
    outputClassDataReceiver.acceptClassData(className, classData);
  }
}
